from django_redis import get_redis_connection
import pickle
import base64


def merge_cart_cookie_to_redis(request, user, response):
    """用户登录时，将 cookie 购物车数据合并到 Redis 购物车数据中
    登录后合并cookie购物车数据到Redis
    :param request: 本次请求对象，获取 cookie 中的数据
    :param response: 本次响应对象，清除 cookie 中的数据
    :param user: 登录用户信息，获取 user_id
    :return: response
    """
    cookie_cart = request.COOKIES.get('carts')
    if cookie_cart:
        # cart_dict: {'14':{'count': 5, 'selected': 'True'}}
        cart_dict = pickle.loads(base64.b64decode(cookie_cart))
    else:
        cart_dict = {}
    conn = get_redis_connection('carts')
    # sku_ids, item = cart_dict.items()
    for sku_id, item in cart_dict.items():
        count = item['count']
        conn.hset('carts_%s' % user.id, sku_id, count)
        if item['selected']:
            conn.sadd('selected_%s' % user.id, sku_id)
        else:
            conn.srem('selected_%s' % user.id, sku_id)

    response.delete_cookie('carts')

    return response










